﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using TbShop.Web.Helpers;
using System.Web.Mvc;

namespace TbShop.Web
{
    public static class ImageUrlHelper
    {
        /// <summary>
        /// 将图片的相对路径（基于应用程序根目录）转换成基于站点的完整相对路径，应对站点下多个应用程序的情况，后期还可以在整个相对路径前追加完整Http路径
        /// </summary>
        /// <param name="helper">扩展UrlHelper</param>
        /// <param name="path">图片相对于应用程序</param>
        /// <returns>完整相对路径</returns>
        public static string ImageUrl(this System.Web.Mvc.UrlHelper helper, string path)
        {
            return helper.Content("~" + path);
        }
        /// <summary>
        /// 保持文件到upload文件夹
        /// </summary>
        /// <param name="file">文件</param>
        /// <param name="uploadFolder">文件夹</param>
        /// <returns>完整相对路径</returns>
        public static string SaveFileToUpload(HttpPostedFileBase file, string uploadFolder)
        {
            var ext = file.FileName.Split('.').Last();
            var path = HttpContext.Current.Server.MapPath("~" + uploadFolder);
            if (!System.IO.Directory.Exists(path))
                System.IO.Directory.CreateDirectory(path);
            var imageUrl = UnityHelper.GetRandom(16) + "." + ext;
            file.SaveAs(path + imageUrl);
            return uploadFolder + imageUrl;
        }
    }
}